package cn.kimming.rpc.remoting.serialization;

import cn.kimming.rpc.common.exception.RpcException;
import com.caucho.hessian.io.Hessian2Input;
import com.caucho.hessian.io.Hessian2Output;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

public class HessianSerialization implements ISerialization{

    private static HessianSerialization instance = new HessianSerialization();

    public static HessianSerialization getInstance() {
        return instance;
    }

    @Override
    public <T> byte[] serialize(T obj) {
        try ( ByteArrayOutputStream os = new ByteArrayOutputStream()) {
            Hessian2Output out = new Hessian2Output(os);
            out.writeObject(obj);
            out.flush();
            return os.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
            throw new RpcException("序列化" + obj + "失败");
        }
    }

    @Override
    public <T> T deserialize(byte[] data, Class<T> cls) {
        try (ByteArrayInputStream is = new ByteArrayInputStream(data)) {
            Hessian2Input in = new Hessian2Input (is);
            Object object = in.readObject();
            return (T) object;
        } catch (IOException e) {
            e.printStackTrace();
            throw new RpcException("反序列化失败");
        }
    }
}
